package 基础语法.网络编程;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDP_learn_单播 {
    public static void main(String[] args) throws Exception {

        Thread senThread = new Thread() {
            @Override
            public void run() {
                try {
                    sendData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Thread receiveThread = new Thread() {
            @Override
            public void run() {
                try {
                    receiveData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        receiveThread.start();

        senThread.start();

    }

    static void sendData() throws Exception {
        // 发送数据
        // 1.
        // 会绑定端口，若空参，会在所有可用的端口中随机选一个发送，否则，就在指定的端口发送
        DatagramSocket ds = new DatagramSocket();

        // 2.
        String sendData = "你好";// 要发送的内容
        byte[] byteData = sendData.getBytes();// 要发送的内容，子节形式
        Integer sendLength = byteData.length;// 本次发送数组多长的内容
        InetAddress targetAddress = InetAddress.getByName("127.0.0.1");// 目标主机地址
        Integer port = 8080;// 目标主机端口
        DatagramPacket dp = new DatagramPacket(byteData, sendLength, targetAddress, port);// 第二个参数值
        // 3.
        ds.send(dp);// 发送数据
        ds.close();
    }

    static void receiveData() throws Exception {

        // 1.
        // 接受的时候一定要指定监听的端口
        Integer port = 8080;// 与发送的者指定 的端口 一致
        DatagramSocket ds = new DatagramSocket(port);

        // 2.接受数据包
        byte[] receiveData = new byte[1024];
        DatagramPacket dp = new DatagramPacket(receiveData, receiveData.length);
        ds.receive(dp);//阻塞值至接收到消息

        // 3.解析数据包

        byte[] data = dp.getData();// 就是receiveData
        int length = dp.getLength();// 获取了多少字节的数据
        InetAddress address = dp.getAddress();// 发送方的IP
        int port1 = dp.getPort();// 发送方的端口

        System.out.println("接收到：" + length + "_" + address + "_" + port1 + "_" + new String(data, 0, length));// 从0号索引开始，length个子节转为字符串

        // 4.释放资源
        ds.close();
    }

}
